package com.security.common;

import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.csrf.DefaultCsrfToken;
import org.springframework.security.web.csrf.LazyCsrfTokenRepository;
import org.springframework.security.web.util.matcher.RequestMatcher;

import com.security.controller.SecurityController;

/**
 * csrf自定义拦截
 * 可添加开放的URL地址
 * @author rui
 *
 */
public class CsrfSecurityRequestMatcher implements RequestMatcher {

	private List<String> execludeUrls;
	private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");

	@Override
	public boolean matches(HttpServletRequest request) {
		System.out.println("=======CsrfSecurityRequestMatcher======");
		//开放的URL
		if (execludeUrls != null && execludeUrls.size() > 0) {
			String servletPath = request.getServletPath();
			for (String url : execludeUrls) {
				if (servletPath.contains(url)) {
					return false;
				}
			}
		}
//		LazyCsrfTokenRepository DefaultCsrfToken = (LazyCsrfTokenRepository)request.getAttribute("_csrf");
//		FilterChainProxy s = new FilterChainProxy();
		return !allowedMethods.matcher(request.getMethod()).matches();
	}
	public List<String> getExecludeUrls() {
		return execludeUrls;
	}
	public void setExecludeUrls(List<String> execludeUrls) {
		this.execludeUrls = execludeUrls;
	}
}
